/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.push.application.impl.channel;

import java.io.IOException;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

/**
 * 实现ResourceLoaderAware接口，启动时能读取到指定的配置文件
 *
 * @author Wangyi
 * @version v1.0
 *
 * @date 2013-8-16
 *
 */
@Component
public class ChannelConfig implements ResourceLoaderAware {
	
	private final Logger log = LoggerFactory.getLogger(this.getClass());
	
	private final Properties props = new Properties();

	@Override
	public void setResourceLoader(ResourceLoader resourceLoader) {
		final String path="classpath:/META-INF/channel/channel.properties";
		//TODO 可以考虑实现类似log4j的配置装载策略
		Resource res=resourceLoader.getResource(path);
		if(res.exists()){
			try {
				props.load(res.getInputStream());
				log.info("推送渠道配置文件{}装载成功", getResourceUrl(res, path));
			} catch (IOException e) {
				log.warn("装载推送渠道配置文件channel.properties出错！", e);
			}
		}
		else{
			log.warn("推送渠道配置文件{}不存在", getResourceUrl(res, path));
		}
	}
	
	private String getResourceUrl(Resource res, String defaultValue){
		String url=defaultValue;
		try {
			url=res.getURL().toString();
		} catch (IOException e) {
			log.warn(e.getMessage(), e);
		}
		return url;
	}
	
	public Properties getProperties(){
		return this.props;
	}

	public String getProperty(String key){
		return this.props.getProperty(key);
	}
	
	public String getProperty(String key, String defaultValue){
		return this.props.getProperty(key, defaultValue);
	}
}
